package net.istore.market.service.user;

import net.istore.market.dao.user.UserDao;
import org.springframework.security.core.userdetails.User;
import net.istore.market.domain.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Ivan_Zhuravel on 1/13/15.
 */
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService, UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {

        //TODO: for refactoring

        net.istore.market.domain.User user = userDao.findByUserName(username);
        List<GrantedAuthority> authorities =
                buildUserAuthority(user.getUserRole());

        return buildUserForAuthentication(user, authorities);

    }

    @Transactional
    public net.istore.market.domain.User addUser(net.istore.market.domain.User user) {
        user.setEnabled(true);
        user.setUserRole(createDefaultUserRoles(user));
        return userDao.addUser(user);
    }

    private User buildUserForAuthentication(net.istore.market.domain.User user,
                                            List<GrantedAuthority> authorities) {
        return new User(user.getUsername(), user.getPassword(),
                user.isEnabled(), true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        return  new ArrayList<GrantedAuthority>(setAuths);
    }

    private Set<UserRole> createDefaultUserRoles(net.istore.market.domain.User user){

        // TODO: ugly code

        UserRole role = new UserRole();
        role.setRole("ROLE_USER");
        role.setUser(user);
        Set<UserRole> result = new HashSet<UserRole>();
        result.add(role);

        return result;
    }
}
